<template>
  <div id="spaceManagePage">
    <a-flex justify="space-between">
      <h2 style="margin-left: 100px">空间管理</h2>
      <a-space style="margin-right: 100px">
        <a-button type="primary" href="/add_space" :icon="h(CloudOutlined)"> 创建空间</a-button>
        <a-button
          type="primary"
          ghost
          href="/space_analyze?queryPublic=1"
          target="_blank"
          :icon="h(BarChartOutlined)"
        >
          公共图库分析
        </a-button>
        <a-button
          type="primary"
          ghost
          href="/space_analyze?queryAll=1"
          target="_blank"
          :icon="h(BarChartOutlined)"
        >
          全部空间分析
        </a-button>
      </a-space>
    </a-flex>
    <div style="margin-bottom: 12px" />
    <!-- 空间搜索表单 -->
    <a-form layout="inline" :model="searchParams">
      <div class="spaceSearchForm">
        <a-form-item label="空间名称" class="spaceName">
          <a-input
            v-model:value="searchParams.spaceName"
            placeholder="模糊搜索空间名称"
            style="min-width: 235px"
            allow-clear
            @change="doSearch"
          />
        </a-form-item>
        <a-form-item label="空间级别">
          <a-select
            v-model:value="searchParams.spaceLevel"
            placeholder="选择空间级别"
            :options="SPACE_LEVEL_OPTIONS"
            allow-clear
            style="min-width: 150px"
            @change="doSearch"
          />
        </a-form-item>
        <a-form-item label="空间类别" name="spaceType">
          <a-select
            v-model:value="searchParams.spaceType"
            :options="SPACE_TYPE_OPTIONS"
            placeholder="选择空间类别"
            allow-clear
            style="min-width: 150px"
            @change="doSearch"
          />
        </a-form-item>
        <a-form-item label="空间管理员ID">
          <a-input
            v-model:value="searchParams.userId"
            placeholder="输入用户Id，精确查找其管理的空间"
            style="min-width: 280px"
            allow-clear
            @change="doSearch"
          />
        </a-form-item>
      </div>
    </a-form>
    <div style="margin-bottom: 16px" />
    <!-- 空间数据表单 -->
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
      :scroll="{ x: 1300, y: 469 }"
      :loading="loading"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'spaceLevel'">
          <div>
            <a-tag v-if="record.spaceLevel === 0" color="blue">
              {{ SPACE_LEVEL_MAP[record.spaceLevel] }}
            </a-tag>
            <a-tag v-if="record.spaceLevel === 1" color="#E4080A" style="opacity: 71%">
              {{ SPACE_LEVEL_MAP[record.spaceLevel] }}
            </a-tag>
            <a-tag v-if="record.spaceLevel === 2" color="#9348A8">
              {{ SPACE_LEVEL_MAP[record.spaceLevel] }}
            </a-tag>
          </div>
        </template>
        <template v-if="column.dataIndex === 'spaceType'">
          <div>
            <a-tag v-if="record.spaceType === 0" color="pink">
              {{ SPACE_TYPE_MAP[record.spaceType] }}
            </a-tag>
            <a-tag v-if="record.spaceType === 1" color="green">
              {{ SPACE_TYPE_MAP[record.spaceType] }}
            </a-tag>
          </div>
        </template>
        <template v-if="column.dataIndex === 'spaceUseInfo'">
          <div>
            已使用容量：{{ formatSize(record.totalSize) }} /
            {{ formatSizeNoDecimalFraction(record.maxSize) }}
          </div>
          <div>已使用 {{ ((record.totalSize / record.maxSize) * 100).toFixed(2) }} % 的空间</div>
          <div>已上传图片：{{ record.totalCount }} 张 / {{ record.maxCount }} 张</div>
          <div>可上传图片： {{ record.maxCount - record.totalCount }} 张</div>
        </template>
        <template v-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-if="column.dataIndex === 'editTime'">
          {{ dayjs(record.editTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space wrap>
            <a-button
              :icon="h(EditOutlined)"
              type="primary"
              :href="`/admin/update_space?id=${record.id}`"
              title="编辑空间信息"
            >
              编辑
            </a-button>
            <!-- 分析空间 -->
            <a-button
              type="primary"
              ghost
              :href="`/space_analyze?spaceId=${record.id}`"
              target="_blank"
              :icon="h(BarChartOutlined)"
              title="对空间数据进行综合分析"
            >
              分析
            </a-button>
            <!-- 删除空间 气泡确认框 -->
            <a-popconfirm
              title="确定删除该空间吗？"
              ok-text="确认"
              cancel-text="取消"
              @confirm="doDelete(record.id)"
              @cancel="cancelDelete"
            >
              <a href="#">
                <a-button
                  :icon="h(DeleteOutlined)"
                  type="primary"
                  danger
                  style="opacity: 95%"
                  title="删除空间"
                  >删除
                </a-button>
              </a>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>
  </div>
</template>
<script lang="ts" setup>
import { computed, onMounted, reactive, ref, h } from 'vue'
import {
  deleteSpaceUsingPost,
  listSpaceByPageUsingPost,
  listSpaceLevelUsingGet,
} from '@/api/spaceController.ts'
import { message } from 'ant-design-vue'
import {
  EditOutlined,
  DeleteOutlined,
  CloudOutlined,
  BarChartOutlined,
} from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import { formatSize, formatSizeNoDecimalFraction } from '../../utils'
import {
  SPACE_LEVEL_MAP,
  SPACE_LEVEL_OPTIONS,
  SPACE_TYPE_MAP,
  SPACE_TYPE_OPTIONS,
} from '../../constants/space.ts'

// 空间管理表格第一行信息
const columns = [
  {
    title: '空间ID',
    dataIndex: 'id',
    width: 185,
  },
  {
    title: '空间名称',
    dataIndex: 'spaceName',
    ellipsis: true,
    width: 185,
  },
  {
    title: '空间级别',
    dataIndex: 'spaceLevel',
    width: 140,
  },
  {
    title: '空间类型',
    dataIndex: 'spaceType',
    width: 140,
  },
  {
    title: '使用情况',
    dataIndex: 'spaceUseInfo',
    width: 240,
  },
  {
    title: '管理员ID',
    dataIndex: 'userId',
    width: 185,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 135,
  },
  {
    title: '编辑时间',
    dataIndex: 'editTime',
    width: 135,
  },
  {
    title: '操作',
    key: 'action',
  },
]

// 定义数据类型
const dataList = ref<API.Space[]>([])
// 分页数据总数
const total = ref(0)
// 定义搜索条件
const searchParams = reactive<API.SpaceQueryRequest>({
  current: 1,
  pageSize: 15,
  sortField: '',
  sortOrder: 'descend',
})
const loading = ref(true)
// 根据搜索条件，远程获取数据
const fetchData = async () => {
  loading.value = true
  const res = await listSpaceByPageUsingPost({
    // ... 是展开运算符，它主要用于将 searchParams 对象中的所有可枚举属性展开并合并到另一个对象中，
    // 从而保证 searchParams 不会受到 fetchData 函数内其他操作的污染
    ...searchParams,
  })
  if (res.data.code === 0 && res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取空间数据失败，' + res.data.message)
  }
  loading.value = false
}

// 首次进入空间管理页面，请求一次默认搜索的空间数据
onMounted(() => {
  fetchData()
})

// 定义分页器参数
const pagination = computed(() => {
  return {
    current: searchParams.current ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    showSizeChange: true,
    // @ts-ignore
    showTotal: (total) => `共 ${total} 条`,
  }
})

// 改变分页展示
const doTableChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  // 重新获取数据
  fetchData()
}

// 搜索空间数据
const doSearch = () => {
  // 重置页码 搜索结束回到第一页
  searchParams.current = 1
  fetchData()
}

/**
 * 删除空间
 * @param id
 */
const doDelete = async (id: String) => {
  // 前端校验一下id是否有效
  if (!id) {
    return
  }
  // @ts-ignore
  const res = await deleteSpaceUsingPost({ id })
  if (res.data.code === 0) {
    message.success('删除成功')
    // 刷新数据
    fetchData()
  } else {
    message.error('删除失败，' + res.data.message)
  }
}

/**
 * 取消删除空间
 * @param e
 */
const cancelDelete = (e: MouseEvent) => {
  message.success('取消删除')
}

/**
 * 用于搜索框默认展示空间级别字段
 */
const getSpaceLevelOptions = async () => {
  const res = await listSpaceLevelUsingGet()
  if (res.data.code === 0 && res.data.data) {
    // @ts-ignore
    tagOptions.value = (res.data.data.tagList ?? []).map((data: String) => {
      return {
        value: data,
        label: data,
      }
    })
    // @ts-ignore
    categoryOptions.value = (res.data.data.categoryList ?? []).map((data: String) => {
      return {
        value: data,
        label: data,
      }
    })
  } else {
    message.error('默认分类标签列表展示失败，' + res.data.message)
  }
}

onMounted(() => {
  getSpaceLevelOptions()
})
</script>

<style scoped>
.spaceSearchForm {
  display: flex;
  margin: auto;
}
</style>
